import { useEffect, useState } from "react";
import { CloseOutlined, DatabaseOutlined } from "@ant-design/icons";
import {message, Popover, Select} from "antd";
import TextArea from "antd/es/input/TextArea";
import { ShowType } from "@/service/general/enumType";
import { KnowledgeBaseModal } from "@/service/request/modal/dataModal";
import { RequestKnowledgeBase } from "@/service/request/modal/requestModal";
import { createKnowledgeBase, getDatasetModels, updateKnowledgeBase } from "@/service/request/requestApi";

import "./addknowledgebase.css";
import { DownArrowSvg, ModelV1Svg, ModelV2Svg, SvgQuest } from "@/app/assets/CustomizeSvg";
import { ResponseModal, ResponseSingleModal } from "@/service/request/modal/responseModal";

interface models {
    agentModels: string[],
    vectorModels: string[]
}

export default function addKnowledgeBase({open, showType, data, setOpen, callback}:{open: boolean, showType?: ShowType, data?: RequestKnowledgeBase,setOpen: (open: boolean) => void,callback?: (param?: any) => void}) {
    const [formTitle, setFormTitle] = useState<string>("创建一个通用知识库");
    const [agentModels, setAgentModels] = useState<string[]>([]);
    const [vectorModels, setVectorModels] = useState<string[]>([]);
    const [agentModelsShow, setAgentModelsShow] = useState<boolean>(false);
    const [vectorModelsShow, setVectorModelsShow] = useState<boolean>(false);
    const [datasetItem, setDatasetItem] = useState<RequestKnowledgeBase>({
        id: null,
        name: "",
        intro: "",
        vectorModel: "",
        agentModel: ""
    });
    // const [itemName, setItemName] = useState<string>("");
    // const [itemIntro, setItemIntro] = useState<string>("");
    // const [commitIng, setCommitIng] = useState<boolean>(false);

    // const indexModels = [{
    //     value: 'qwen2.5:7b',
    //     label: 'qwen2.5:7b',
    // }]
    useEffect(() => {
        if (open) {
            Initialize();
        } else {
            Dispose();
        }
    }, [open]);

    const Initialize = () => {
        loadModels();
        setFormTitle("创建一个通用知识库");
        if (showType && showType === ShowType.UPDATE) {
            if (!data || data.id === null) {
                message.error(`数据错误，缺少id`);
                setOpen(false);
                return;
            }
            setFormTitle(`修改 "${data.name}"`);
            setDatasetItem({
                id: data.id,
                name: data.name,
                intro: data.intro,
                agentModel: data.agentModel,
                vectorModel: data.vectorModel
            });
        }
    }

    const Dispose = () => {
        setDatasetItem({
            id: null,
            name: "",
            intro: "",
            agentModel: "",
            vectorModel: ""
        });
    }

    const loadModels = () => {
        getDatasetModels().then((res: ResponseSingleModal<models>) => {
            if (res.code === 200 && res.success && res.result) {
                setAgentModels(res.result.agentModels);
                setVectorModels(res.result.vectorModels);
            } else if (res.message && res.message.length > 0) {
                message.error(res.message);
            }
        }).catch((err) => {
            console.log("获取模型失败");
        });
    }

    const changeValue = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        const {name , value} = e.target;
        setDatasetItem((item) => ({
            ...item,
            [name]: value,
        }));
    }

    const changeDatasetItem = ({key, value}:{key: string, value: string}) => {
        if (isValidKey(datasetItem, key)) {
            setDatasetItem((item) => ({
                ...item,
                [key]: value
            }));
        }
    }

    const isValidKey = <T extends Object>(obj: T, key: string | number | symbol): key is keyof T => {
        return Object.prototype.hasOwnProperty.call(obj, key);
    }

    const saveDataset = () => {
        if (!datasetItem?.name || datasetItem.name === "") {
            message.error("名称不能为空");
            return;
        }
        
        commitDataset();
    }

    const commitDataset = () => {
        if (datasetItem) {
            if (showType === ShowType.CREATE) {
                const param: RequestKnowledgeBase = {
                    ...datasetItem,
                    vectorModel: datasetItem.vectorModel || vectorModels[0],
                    agentModel: datasetItem.agentModel || agentModels[0]
                }
                createKnowledgeBase(param).then((res: ResponseModal<boolean>) => {     
                    if (res.code === 200 && res.success && res.result) {
                        message.success("创建成功");
                        setOpen(false);
                        if (callback) {
                            callback();
                        }
                    } else if (res.message && res.message.length > 0) {
                        message.error(res.message);
                    } else {
                        message.error("创建失败");
                    }
                }).catch((error) => {
                    console.error(error);
                });
            } else if (showType === ShowType.UPDATE) {
                updateKnowledgeBase(datasetItem).then((res: ResponseModal<boolean>) => {
                    if (res.code === 200 && res.success && res.result) {
                        message.success("修改成功");
                        setOpen(false);
                        if (callback) {
                            callback(datasetItem);
                        }
                    } else if (res.message && res.message.length > 0) {
                        message.error(res.message);
                    } else {
                        message.error("修改失败");
                    }
                }).catch((error) => {
                    console.error(error);
                });
            }
        }
    }

    const hidePopover = () => {
        setVectorModelsShow(false);
        setAgentModelsShow(false);
    }

    return (
        <div className="edit-modal" style={{
            display: open ? 'block' : 'none',
        }} 
        // onClick={() => setOpen(false)}
        >
            <div className="view-modal">
                <div className="modal-content" onClick={(event) => {event.stopPropagation();hidePopover()}}>
                    <div className="modal-title">
                        <div className="title-info">
                            <div className="title-icon"><DatabaseOutlined className="title-icon-i" /></div>
                            <div>{formTitle}</div>
                        </div>
                        <div className="modal-close" onClick={() => {setOpen(false);}}>
                            <CloseOutlined className="modal-icon-close" />
                        </div>
                    </div>
                    <div className="w-full flex flex-col items-center justify-center gap-3 p-5">
                        <div className="w-full flex flex-col items-start justify-center gap-1">
                            <div>取个名字</div>
                            <div className="w-full flex flex-row items-start justify-center pl-4">
                                <div className="data-name-icon"><DatabaseOutlined className="data-name-icon-i" /></div>
                                <div className="w-full h-10 px-3 rounded-lg bg-gray-100 border border-gray-100 shadow-[0_0_5px] shadow-transparent has-[input:focus-within]:border-blue-400 has-[input:focus-within]:shadow-blue-400 has-[input:focus-within]:bg-white">
                                    <input type="text" name="name" value={datasetItem.name} className="w-full h-full border-none outline-none bg-transparent" onChange={(e) => {changeValue(e)}} placeholder="名称"></input>
                                </div>
                            </div>
                        </div>
                        <div className="w-full flex flex-col items-start justify-center gap-1">
                            <div>介绍</div>
                            <div className="w-full h-32 flex flex-col itemc justify-center">
                                <div className="flex flex-row items-center justify-center w-full h-full p-3 rounded-lg border bg-gray-100 border-gray-200 shadow-[0_0_5px_rgb(96,165,250,0.1)] shadow-transparent hover:border-blue-400 has-[textarea:focus-within]:border-blue-400 has-[textarea:focus-within]:shadow-blue-400 has-[textarea:focus-within]:bg-white">
                                    <textarea 
                                    className="w-full h-full border-none outline-none bg-transparent resize-none" 
                                    name="intro"
                                    value={datasetItem.intro}
                                    onChange={(e) => {changeValue(e)}}
                                    maxLength={200} 
                                    placeholder="介绍这个知识库"
                                    />
                                </div>
                                <div className="w-full flex flex-row items-center justify-end px-1">{datasetItem.intro?.length || 0} / 200</div>
                            </div>
                        </div>
                        {
                            showType === ShowType.CREATE ? (
                                <>
                                    <div className="w-full h-fit flex flex-col items-center justify-center gap-3">
                                        <div className="w-full h-fit flex flex-row items-center justify-between">
                                            <div className="flex-1 index-model-label model-label">
                                                <div className="label-text text-nowrap">索引模型</div>
                                                <Popover content={
                                                    <>
                                                        <div className="max-w-72 px-2 py-1">
                                                            索引模型可以将自然语言转成向量，用于进行语义检索。<br />
                                                            注意，不同索引模型无法一起使用，选择完索引模型后将无法修改
                                                        </div>
                                                    </>
                                                }
                                                trigger="hover"
                                                overlayInnerStyle={{margin: 0, padding: 0}}
                                                >
                                                <div className="label-icon-quest icon-quest cursor-pointer"><SvgQuest color="#575B66"/></div>
                                                </Popover>
                                            </div>
                                            <div className="flex-[2] w-full index-model-select model-select">
                                                <Popover 
                                                content={
                                                    <>
                                                        <div className="scrollbar-style w-full max-h-60 h-fit px-2 py-2 rounded-lg overflow-y-auto">
                                                            <div className="w-full h-fit flex flex-col items-center justify-center gap-2">
                                                                {
                                                                    vectorModels.map((item, index) => (
                                                                        <>
                                                                            <div 
                                                                            key={`vectorModel_select_${index}`}
                                                                            className="w-full h-fit flex flex-row items-center justify-start cursor-pointer p-2 rounded-lg hover:bg-gray-200"
                                                                            onClick={() => {changeDatasetItem({key: "vectorModel", value: item});setVectorModelsShow(false);}}
                                                                            >
                                                                                <div className="w-5 flex flex-row items-center justify-center text-blue-400">
                                                                                    <ModelV2Svg width={`100%`} height={`100%`} />
                                                                                </div>
                                                                                <div>{item}</div>
                                                                            </div>
                                                                        </>
                                                                    ))
                                                                }
                                                            </div>
                                                        </div>
                                                    </>
                                                } 
                                                arrow={false} 
                                                open={vectorModelsShow}
                                                placement="bottom"
                                                overlayInnerStyle={{margin: 0,padding: 0}}
                                                overlayStyle={{width: "100%"}}
                                                getPopupContainer={(node) => node}
                                                >
                                                    <div className="w-full relative flex flex-row items-center justify-between cursor-pointer shadow-[0_0_5px] shadow-transparent border border-gray-300 rounded-lg py-2 px-4 hover:border-blue-300 hover:shadow-blue-300" onClick={(event) => {
                                                        event.stopPropagation();
                                                        hidePopover();
                                                        setVectorModelsShow(!vectorModelsShow);
                                                        }}>
                                                        <div className="flex flex-row items-center justify-center gap-2">
                                                            <div className="w-5 flex flex-row items-center justify-center text-blue-400">
                                                                <ModelV2Svg width={`100%`} height={`100%`} />
                                                            </div>
                                                            <div>{datasetItem.vectorModel || vectorModels[0]}</div>
                                                        </div>
                                                        <div className="w-5 flex flex-row items-center justify-center text-gray-400">
                                                            <DownArrowSvg width={`100%`} height={`100%`} />
                                                        </div>
                                                    </div>
                                                </Popover>
                                            </div>
                                        </div>
                                        <div className="w-full h-fit flex flex-row items-center justify-between">
                                            <div className="flex-1 text-model-label model-label">
                                                <div className="label-text text-nowrap">文本理解模型</div>
                                                <Popover content={
                                                    <>
                                                        <div className="max-w-72 px-2 py-1">
                                                            用于增强索引和&nbsp;QA&nbsp;生成
                                                        </div>
                                                    </>
                                                }
                                                trigger="hover"
                                                overlayInnerStyle={{margin: 0, padding: 0}}
                                                >
                                                    <div className="label-icon-quest icon-quest cursor-pointer"><SvgQuest color="#575B66"/></div>
                                                </Popover>
                                            </div>
                                            <div className="flex-[2] w-full text-model-select model-select">
                                                <Popover
                                                content={
                                                    <>
                                                        <div className="scrollbar-style w-full max-h-60 h-fit px-2 py-2 rounded-lg overflow-y-auto">
                                                            <div className="w-full h-fit flex flex-col items-center justify-center gap-2">
                                                                {
                                                                    agentModels.map((item, index) => (
                                                                        <>
                                                                            <div 
                                                                            key={`vectorModel_select_${index}`}
                                                                            className="w-full h-fit flex flex-row items-center justify-start cursor-pointer p-2 rounded-lg hover:bg-gray-200"
                                                                            onClick={() => {changeDatasetItem({key: "agentModel", value: item});setAgentModelsShow(false);}}
                                                                            >
                                                                                <div className="w-5 flex flex-row items-center justify-center text-blue-400">
                                                                                    <ModelV2Svg width={`100%`} height={`100%`} />
                                                                                </div>
                                                                                <div>{item}</div>
                                                                            </div>
                                                                        </>
                                                                    ))
                                                                }
                                                            </div>
                                                        </div>
                                                    </>
                                                } 
                                                arrow={false} 
                                                open={agentModelsShow}
                                                placement="bottom"
                                                overlayInnerStyle={{margin: 0,padding: 0}}
                                                overlayStyle={{width: "100%"}}
                                                getPopupContainer={(node) => node}
                                                >
                                                    <div 
                                                    className="w-full relative flex flex-row items-center justify-between cursor-pointer shadow-[0_0_5px] shadow-transparent border border-gray-300 rounded-lg py-2 px-4 hover:border-blue-300 hover:shadow-blue-300"
                                                    onClick={(event) => {
                                                        event.stopPropagation();
                                                        hidePopover();
                                                        setAgentModelsShow(!agentModelsShow);
                                                        }}
                                                    >
                                                        <div className="flex flex-row items-center justify-center gap-2">
                                                            <div className="w-5 flex flex-row items-center justify-center text-blue-400">
                                                                <ModelV2Svg width={`100%`} height={`100%`} />
                                                            </div>
                                                            <div>{datasetItem.agentModel || agentModels[0]}</div>
                                                        </div>
                                                        <div className="w-5 flex flex-row items-center justify-center text-gray-400">
                                                            <DownArrowSvg width={`100%`} height={`100%`} />
                                                        </div>
                                                    </div>
                                                </Popover>
                                            </div>
                                        </div>
                                    </div>
                                </>
                            ):(<></>)
                        }
                        
                    </div>
                    <div className="modal-btn">
                        <div className="btn-close mr-4 py-1.5 px-4 border rounded-md cursor-pointer hover:bg-[#e1e1e1]" onClick={() => setOpen(false)}>关闭</div>
                        <div className="btn-create py-1.5 px-4 border rounded-md cursor-pointer bg-[#0D6EFD] text-white hover:bg-[rgba(13,110,253,0.8)]" onClick={() => {saveDataset()}}>确认创建</div>
                    </div>
                </div>
            </div>
        </div>
    );
}